/* Chibi IT Play  - Copyright (c) 2007, Juan Linietsky */
/*

License:

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
            
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include "itplay.h"

#include <SDL.h>
#include <SDL_main.h>

/** IT_AudioLock Implementation */

void lock_audio() {
	
	SDL_LockAudio();
}

void unlock_audio() {
	
	SDL_UnlockAudio();
}

/** IT_MemoryManager Implementation */

void * alloc_mem(it_u32 p_size,IT_MemoryAllocType p_alloc_type) {
	
	return malloc(p_size);
}

void free_mem(void *p_mem,IT_MemoryAllocType p_alloc_type) {
	
	free(p_mem);
}

/** IT_FileIO Implementation **/

FILE *f=NULL;
it_bool f_be;

it_bool fileio_in_use() {
	
	return f?it_true:it_false;		
}

IT_FileIOError fileio_open(const char *p_file,it_bool p_big_endian_mode) {
	
	if (f) 
		return IT_FILE_ERROR_IN_USE;
	
	f=fopen(p_file,"rb");
	if (!f)
		return IT_FILE_ERROR_CANT_OPEN;
	
	f_be=p_big_endian_mode;
	return IT_FILE_OK;
}

it_u8 fileio_get_u8() {
	
	
	it_u8 b;
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return 0;	
	}
	
	fread(&b,1,1,f);
	
	return b;
}

it_u16 fileio_get_u16() {
	
	it_u8 a,b;
	it_u16 c;
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return 0;	
	}
	
	if (!f_be) {
		a=fileio_get_u8();
		b=fileio_get_u8();
	} else {
		
		b=fileio_get_u8();
		a=fileio_get_u8();		
	}
	
	c=((it_u16)b << 8 ) | a;
	
	return c;
}

it_u32 fileio_get_u32() {
	
	it_u16 a,b;
	it_u32 c;
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return 0;	
	}
	
	if (!f_be) {
		a=fileio_get_u16();
		b=fileio_get_u16();
	} else {
		
		b=fileio_get_u16();
		a=fileio_get_u16();		
	}
	
	c=((it_u32)b << 16 ) | a;	
	
	return c;
}

void fileio_get_byte_array(it_u8 *p_dst,it_u32 p_count) {
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return;	
	}
	
	fread(p_dst,p_count,1,f);
}

void fileio_seek_pos(it_u32 p_offset) {
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return;	
	}
	
	fseek(f,p_offset,SEEK_SET);
}

it_u32 fileio_get_pos() {
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return 0;	
	}
	
	return ftell(f);
}

it_bool fileio_eof_reached() {
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return it_true;	
	}
	
	return feof(f)?it_true:it_false;
}


/** IT_Mixer read callback **/
 
IT_Mixer *softmix;

#define INTERNAL_BUFFER_SIZE 2048
 static it_s32 mix_buff[INTERNAL_BUFFER_SIZE*2];
 
void audio_callback(void *userdata, Uint8 *stream, int len) {


	int todo=len/4; /* since dst is 16 bits, stereo | convert bytes -> frames */
	int i;
	Sint16 *dst_buff=(Sint16*)stream;
	
	while (todo) {
	
		int to_mix=todo;
		if (to_mix>INTERNAL_BUFFER_SIZE)
			to_mix=INTERNAL_BUFFER_SIZE;
			
		todo-=to_mix;
			
		for (i=0;i<to_mix*2;i++) {
		
			mix_buff[i]=0; /* clean up target buffer */
		}
		it_softmixer_mix(softmix,mix_buff,to_mix);
		
		for (i=0;i<to_mix*2;i++) {
			
			dst_buff[i]=mix_buff[i]>>16; /* conver to 16 bits */			
		}
	
	}

}


void fileio_close() {
	
	if (!f) {
		
		fprintf(stderr,"File Not Open!");
		return;	
	}
	
	fclose(f);
	f=NULL;
}



int main(int argc, char *argv[]) {
	
	
	IT_AudioLock audio_lock;
	IT_MemoryManager memory_manager;
	IT_FileIO file_io;
	IT_Instance instance;
	IT_Player* player;	
	
	SDL_AudioSpec desired_audio;
	SDL_AudioSpec obtained_audio;
	IT_Song *song;
	IT_LoaderError song_error;
	
	if (argc<=1) {
		printf("usage: itplay_sdl file.it\n");
		return 255;
	}	
		   
	SDL_Init(SDL_INIT_AUDIO);
		  
	/** AUDIO LOCK **/
	

	
	audio_lock.lock=lock_audio;
	audio_lock.unlock=unlock_audio;
		
	/** MEMORY MANAGER **/
	
	
	memory_manager.alloc=alloc_mem;
	memory_manager.free=free_mem;
	
	/** FILE IO **/
	
	
	file_io.in_use=fileio_in_use;
	file_io.open=fileio_open;
	file_io.get_u8=fileio_get_u8;
	file_io.get_u16=fileio_get_u16;
	file_io.get_u32=fileio_get_u32;
	file_io.get_u8_array=fileio_get_byte_array;
	file_io.seek=fileio_seek_pos;
	file_io.get_pos=fileio_get_pos;
	file_io.eof_reached=fileio_eof_reached;
	file_io.close=fileio_close;
	
	/** MIXER **/
	
	
	desired_audio.freq=44100;
	desired_audio.format=AUDIO_S16SYS;	
	desired_audio.channels=2;
	desired_audio.samples=2048;
	desired_audio.callback=audio_callback;
	desired_audio.userdata=0;
	
	SDL_OpenAudio(&desired_audio,&obtained_audio);

	if (obtained_audio.channels!=2) {
		
		printf("Stereo not supported");
		return 255;	
	}

	/** SOFTMIX */

	softmix = it_softmixer_create(44100,IT_CONSTANT_DEFAULT_MAX_VOICES,&memory_manager);
	/** INSTANCE **/
	
	it_instance_create(&instance,&memory_manager,&file_io,softmix,&audio_lock,NULL);

	/** SONG **/
	
	song = it_song_create(&instance);
	
/*	it_loader_set_recompress_all_samples(it_true); */
	song_error = it_instance_load_song(&instance,song,argv[1],IT_LOADER_FLAGS_DEFAULT);


	
	switch (song_error) {
		
		case IT_LOADER_OK: printf("Loaded Song OK\n"); break;
		case IT_LOADER_UNCONFIGURED: printf("Loader Error: Unconfigured\n"); break;
		case IT_LOADER_ERROR_FILEIO_IN_USE: printf("Loader Error: File in Use\n"); break;
		case IT_LOADER_ERROR_FILE_CANT_OPEN: printf("Loader Error: Can't Open\n"); break;
		case IT_LOADER_ERROR_FILE_UNRECOGNIZED: printf("Loader Error: File Unrecognized\n"); break;
		case IT_LOADER_ERROR_OUT_OF_MEMORY: printf("Loader Error: Out of Memory\n"); break;
		case IT_LOADER_ERROR_FILE_CORRUPT: printf("Loader Error: File is Corrupted\n"); break;		
	}
	
	if (song_error)
		return 255;
	
	player = it_player_create(&instance);
	it_player_set_song(player,song);
	it_player_play(player);
	
	SDL_PauseAudio(0);

	while(1) { SDL_Delay(50); }
	
	
	return 0;
}
